package com.project.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.project.Boot;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan(basePackageClasses = Boot.class)
@MapperScan("com.project.mapper") //定义指定包中的mapper文件扫描
@EnableTransactionManagement //允许使用@Transactional进行配置事务
public class MyBatisConfig {

    /**
     * 进行数据源配置,得到数据源
     *
     * @return 数据源对象
     */
    @Bean
    public DataSource getDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:12345/myData21721?characterEncoding=utf-8&allowMultiQueries=true");
        dataSource.setUsername("root");
        dataSource.setPassword("1122");
        dataSource.setMaxActive(100);
        dataSource.setMinIdle(20);
        dataSource.setMaxWait(1000);
        return dataSource;
    }

    /**
     * 配置会话工厂
     *
     * @return 会话工厂对象
     */
    @Bean(name = "factory")
    public SqlSessionFactoryBean getFactory() {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //设置数据源
        factoryBean.setDataSource(this.getDataSource());
        //读取mybatis主配置文件
        factoryBean.setConfigLocation(new ClassPathResource("MyBatisConfig.xml"));
        return factoryBean;
    }

    /**
     * 配置事务管理器
     *
     * @return 事务管理器对象
     */
    @Bean
    public TransactionManager getTransaction() {
        DataSourceTransactionManager trans = new DataSourceTransactionManager();
        trans.setDataSource(this.getDataSource());
        return trans;
    }
}